package com.zebra.register;

import com.zebra.common.concurrent.ZebraExecutorManager;
import com.zebra.remoting.IpInfoProperties;
import com.zebra.remoting.config.*;
import com.zebra.remoting.protocol.CommandModelManager;
import com.zebra.remoting.tms.TmsToRegisterMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;



@Component
@Slf4j
public class RegisterStartService {


    @Value("${server.port}")
    private int port;

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private ServerRedisService serverRedisService;
    @Autowired
    private RegisterServerService registerServerService;

    /**
     * start server Info write redis
     * @throws Exception
     */
    public void start(IpInfoProperties properties, RegisterClientHandler clientHandler) throws Exception {
        if (null == properties || properties.isNull()){
            throw new Exception("IpInfoProperties is null");
        }
        CommandModelManager.initializeCommandCode(null);

        RegisterServerInfo registerServerInfo = new RegisterServerInfo();
        registerServerInfo.setServerId(serverRedisService.getRaId());
        registerServerInfo.setAppName(appName);
        registerServerInfo.setPort(port);
        registerServerInfo.setInIP(properties.getIpIn());
        registerServerInfo.setOutIP(properties.getIpOut());
        registerServerInfo.setOnline(1);

        serverRedisService.addRegisterServer(registerServerInfo);
        serverRedisService.addCMDS(BasisCommandCode.toListProfile());
        RegisterClient.getInstance().start(clientHandler);
        ZebraExecutorManager.getInstance().start(8);
        log.info("Clear server info........");
        doCheck();
        registerServerService.printRegisterLog();
        log.info("Register start success");
//        RegisterConfigInfoManager.getInstance().getRelationManager().lastExamine();
    }

    //中途启动则需要 链接所有的 GW TMS
    private void doCheck() throws Exception {
        doGateway();
        doTms();
    }


    private void doGateway(){
        List<GatewayServerInfo> gwList = serverRedisService.findGwAll();
        if (null == gwList || gwList.isEmpty()){
            return;
        }
        gwList.forEach(gw -> {
            try {
                registerServerService.registerGateway(gw, false);
            } catch (Exception e) {
                serverRedisService.removeGw(gw.getServerId()); // 需要调用Ra leader 删除
                log.error("GW connection failure remove!");
            }
        });
    }


    private void doTms(){
        List<TmsServerInfo> tmList = serverRedisService.findTmsAll();
        if (null == tmList || tmList.isEmpty()){
            return;
        }
        tmList.forEach(tms -> {
            try {
                TmsToRegisterMessage toRegisterMessage = new TmsToRegisterMessage();
                toRegisterMessage.setServerInfo(tms);
                registerServerService.registerTms(toRegisterMessage, false);
            } catch (Exception e) {
                serverRedisService.removeTms(tms.getServerId());  //需要调用Ra leader 删除
                log.error("TMS connection failure remove!");
            }
        });

    }


}
